<template>
  <div class="opportunity-detail">
    <!-- 返回按钮 -->
    <el-button type="text" @click="goBack" class="back-button">
      <el-icon><ArrowLeft /></el-icon> 返回列表
    </el-button>

    <div v-loading="loading">
      <!-- 机会基本信息 -->
      <div class="basic-info" v-if="opportunityData">
        <h1>{{ opportunityData.title }}</h1>
        <div class="meta-info">
          <span class="status-tag" :class="getStatusClass(opportunityData.opportunityStatus)">
            {{ getStatusText(opportunityData.opportunityStatus) }}
          </span>
          <span><el-icon><View /></el-icon> 浏览: {{ opportunityData.viewCount || 0 }}</span>
          <span><el-icon><ChatDotRound /></el-icon> 评论: {{ opportunityData.commentCount || 0 }}</span>
          <span><el-icon><Calendar /></el-icon> 发布时间: {{ getFormattedDate(opportunityData.createTime) }}</span>
        </div>
      </div>

      <!-- 机会内容 -->
      <div class="opportunity-content" v-if="opportunityData">
        <div class="detail-content" v-html="opportunityData.content"></div>
      </div>
    </div>

    <!-- 评论区域 -->
    <div class="comments-section" v-if="opportunityData">
      <h3 class="comments-title">评论区 ({{ total }})</h3>
      
      <!-- 评论输入框 -->
      <div class="comment-input">
        <el-input
          v-model="newComment"
          type="textarea"
          :rows="3"
          :maxlength="maxCommentLength"
          placeholder="请输入您的评论..."
          show-word-limit
          @input="updateCommentLength"
        />
        <div class="comment-input-footer">
          <span class="remaining-chars">还可输入 {{ remainingChars }} 字</span>
          <el-button
            type="primary"
            @click="submitComment"
            :disabled="!newComment.trim() || submitting"
            :loading="submitting"
          >
            发表评论
          </el-button>
        </div>
      </div>

      <!-- 评论列表 -->
      <div class="comments-list" v-loading="commentsLoading">
        <el-empty v-if="comments.length === 0" description="暂无评论，来发表第一条评论吧"></el-empty>

        <div
          v-for="comment in comments"
          :key="comment.commentId"
          class="comment-item"
        >
          <!-- 主评论 -->
          <div class="comment-main">
            <el-avatar :src="comment.commenterAvatar || defaultAvatar" />
            <div class="comment-content">
              <div class="comment-user">{{ comment.commenterUser }}</div>
              <div class="comment-text">{{ comment.content }}</div>
              <div class="comment-footer">
                <span class="comment-time">{{ getFormattedDate(comment.createTime) }}</span>
                <div class="comment-actions">
                  <el-button
                    type="text"
                    @click="showReplyInput(comment.commentId)"
                  >
                    回复
                  </el-button>
                  <el-button
                    v-if="canDeleteComment(comment)"
                    type="text"
                    @click="handleDeleteComment(comment.commentId)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 回复输入框 -->
          <div
            v-if="activeReplyId === comment.commentId"
            class="reply-input"
          >
            <el-input
              v-model="replyContent"
              type="textarea"
              :rows="2"
              :maxlength="maxCommentLength"
              :placeholder="replyToUser ? `回复 ${replyToUser}:` : '请输入回复内容...'"
              show-word-limit
              @input="updateReplyLength"
            />
            <div class="reply-input-footer">
              <span class="remaining-chars">还可输入 {{ remainingReplyChars }} 字</span>
              <div class="reply-actions">
                <el-button @click="cancelReply">取消</el-button>
                <el-button
                  type="primary"
                  @click="submitReply(comment.commentId)"
                  :disabled="!replyContent.trim() || replySubmitting"
                  :loading="replySubmitting"
                >
                  回复
                </el-button>
              </div>
            </div>
          </div>

          <!-- 回复列表 -->
          <div
            v-if="comment.replies && comment.replies.length > 0"
            class="replies-list"
          >
            <div
              v-for="reply in comment.replies"
              :key="reply.commentId"
              class="reply-item"
            >
              <el-avatar :src="reply.commenterAvatar || defaultAvatar" size="small" />
              <div class="reply-content">
                <div class="reply-user">
                  {{ reply.commenterUser }}
                  <template v-if="reply.replyToUser">
                    回复 {{ reply.replyToUser }}
                  </template>
                </div>
                <div class="reply-text">{{ reply.content }}</div>
                <div class="reply-footer">
                  <span class="reply-time">{{ getFormattedDate(reply.createTime) }}</span>
                  <div class="reply-actions">
                    <el-button
                      type="text"
                      @click="showReplyInput(comment.commentId, reply.commenterUser)"
                    >
                      回复
                    </el-button>
                    <el-button
                      v-if="canDeleteComment(reply)"
                      type="text"
                      @click="handleDeleteComment(reply.commentId)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <el-pagination
          v-if="total > 0"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, View, ChatDotRound, Calendar } from '@element-plus/icons-vue'
import {
  getOpportunityDetail
} from '@/api/opportunity'
import { useUserStore } from '@/store/user'
import request from '@/api/request'

export default {
  name: 'OpportunityDetail',
  components: {
    ArrowLeft,
    View,
    ChatDotRound,
    Calendar
  },
  props: {
    opportunityId: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()
    const loading = ref(false)
    const commentsLoading = ref(false)
    const opportunityData = ref(null)
    const comments = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const newComment = ref('')
    const replyContent = ref('')
    const activeReplyId = ref(null)
    const replyToUser = ref(null)
    const defaultAvatar = '/src/assets/user-avatar.svg'
    const submitting = ref(false)
    const replySubmitting = ref(false)
    const maxCommentLength = 500
    const remainingChars = ref(maxCommentLength)
    const remainingReplyChars = ref(maxCommentLength)

    // 更新评论剩余字数
    const updateCommentLength = () => {
      remainingChars.value = maxCommentLength - (newComment.value?.length || 0)
    }

    // 更新回复剩余字数
    const updateReplyLength = () => {
      remainingReplyChars.value = maxCommentLength - (replyContent.value?.length || 0)
    }

    // 从路由获取ID参数或从props获取
    const getOpportunityId = () => {
      return props.opportunityId || route.params.id
    }

    // 格式化日期
    const getFormattedDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      }).format(date)
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        0: '未发布',
        1: '已发布',
        2: '已过期'
      }
      return statusMap[status] || '未知状态'
    }

    // 获取状态样式
    const getStatusClass = (status) => {
      const statusClassMap = {
        0: 'status-draft',
        1: 'status-published',
        2: 'status-expired'
      }
      return statusClassMap[status] || ''
    }

    // 获取机会详情
    const fetchOpportunityDetail = async () => {
      loading.value = true
      const id = getOpportunityId()
      console.log('获取机会详情，ID:', id)
      try {
        const res = await getOpportunityDetail(id)
        console.log('机会详情响应:', res)
        if (res.code === 200 || res.code === 0) {
          opportunityData.value = res.data
          console.log('机会详情数据:', opportunityData.value)
        } else {
          ElMessage.error(res.message || '获取机会详情失败')
        }
      } catch (error) {
        console.error('获取机会详情出错:', error)
        ElMessage.error('获取机会详情失败')
      } finally {
        loading.value = false
      }
    }

    // 获取评论列表
    const fetchComments = async () => {
      commentsLoading.value = true
      const id = getOpportunityId()
      try {
        const res = await request({
          url: '/opportunityComment/page',
          method: 'get',
          params: {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            opportunityId: id
          }
        })
        console.log('评论列表响应:', res)
        if (res.code === 200 || res.code === 0) {
          comments.value = res.data.records || []
          total.value = res.data.total || 0
          console.log('评论数据:', comments.value.length, '条评论')
          // 获取每个评论的回复
          if (comments.value.length > 0) {
            await Promise.all(
              comments.value.map(async (comment) => {
                try {
                  const repliesRes = await request({
                    url: '/opportunityComment/listReply',
                    method: 'get',
                    params: {
                      topId: comment.commentId,
                      parentId: comment.commentId
                    }
                  })
                  if (repliesRes.code === 200 || repliesRes.code === 0) {
                    comment.replies = repliesRes.data || []
                    console.log(`评论ID ${comment.commentId} 的回复:`, comment.replies.length, '条')
                  } else {
                    console.warn('获取回复失败:', repliesRes.message)
                    comment.replies = []
                  }
                } catch (error) {
                  console.error('获取回复错误:', error)
                  comment.replies = []
                }
              })
            )
          }
        } else {
          ElMessage.error(res.message || '获取评论列表失败')
          comments.value = []
          total.value = 0
        }
      } catch (error) {
        console.error('获取评论列表出错:', error)
        ElMessage.error('获取评论列表失败')
        comments.value = []
        total.value = 0
      } finally {
        commentsLoading.value = false
      }
    }

    // 提交评论
    const submitComment = async () => {
      if (!newComment.value.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }
      
      submitting.value = true
      const id = getOpportunityId()
      try {
        const res = await request({
          url: '/opportunityComment/addComment',
          method: 'post',
          data: {
            opportunityId: id,
            content: newComment.value,
            commenterUser: userStore.nickname || userStore.username || '匿名用户',
            commenterAvatar: userStore.avatar || defaultAvatar
          }
        })
        if (res.code === 200 || res.code === 0) {
          ElMessage.success('评论发表成功')
          newComment.value = ''
          remainingChars.value = maxCommentLength
          await fetchComments()
        } else {
          ElMessage.error(res.message || '评论发表失败')
        }
      } catch (error) {
        console.error('发表评论出错:', error)
        ElMessage.error(error.response?.data?.message || '评论发表失败，请检查网络连接')
      } finally {
        submitting.value = false
      }
    }

    // 显示回复输入框
    const showReplyInput = (commentId, replyToName = null) => {
      activeReplyId.value = commentId
      replyToUser.value = replyToName
      replyContent.value = ''
      remainingReplyChars.value = maxCommentLength
    }

    // 取消回复
    const cancelReply = () => {
      activeReplyId.value = null
      replyToUser.value = null
      replyContent.value = ''
      remainingReplyChars.value = maxCommentLength
    }

    // 提交回复
    const submitReply = async (parentId) => {
      if (!replyContent.value.trim()) {
        ElMessage.warning('请输入回复内容')
        return
      }
      
      replySubmitting.value = true
      const id = getOpportunityId()
      try {
        const res = await request({
          url: '/opportunityComment/addComment',
          method: 'post',
          data: {
            opportunityId: id,
            parentId,
            content: replyContent.value,
            commenterUser: userStore.nickname || userStore.username || '匿名用户',
            commenterAvatar: userStore.avatar || defaultAvatar,
            replyToUser: replyToUser.value
          }
        })
        if (res.code === 200 || res.code === 0) {
          ElMessage.success('回复发表成功')
          cancelReply()
          await fetchComments()
        } else {
          ElMessage.error(res.message || '回复发表失败')
        }
      } catch (error) {
        console.error('发表回复出错:', error)
        ElMessage.error(error.response?.data?.message || '回复发表失败，请检查网络连接')
      } finally {
        replySubmitting.value = false
      }
    }

    // 删除评论
    const handleDeleteComment = async (commentId) => {
      try {
        await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
          type: 'warning'
        })
        const res = await request({
          url: `/opportunityComment/${commentId}`,
          method: 'delete'
        })
        if (res.code === 200 || res.code === 0) {
          ElMessage.success('评论删除成功')
          await fetchComments()
        } else {
          ElMessage.error(res.message || '删除评论失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除评论出错:', error)
          ElMessage.error('删除评论失败')
        }
      }
    }

    // 判断是否可以删除评论
    const canDeleteComment = (comment) => {
      return comment.commenterUser === userStore.username
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchComments()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchComments()
    }

    // 返回列表
    const goBack = () => {
      router.push('/opportunity')
    }

    onMounted(() => {
      fetchOpportunityDetail()
      fetchComments()
    })

    watch(() => props.opportunityId, (newVal, oldVal) => {
      if (newVal !== oldVal) {
        fetchOpportunityDetail()
        currentPage.value = 1
        fetchComments()
      }
    })

    watch(() => route.params.id, (newVal, oldVal) => {
      if (newVal !== oldVal) {
        fetchOpportunityDetail()
        currentPage.value = 1
        fetchComments()
      }
    })

    return {
      loading,
      commentsLoading,
      opportunityData,
      comments,
      total,
      currentPage,
      pageSize,
      newComment,
      replyContent,
      activeReplyId,
      replyToUser,
      defaultAvatar,
      submitting,
      replySubmitting,
      maxCommentLength,
      remainingChars,
      remainingReplyChars,
      updateCommentLength,
      updateReplyLength,
      getFormattedDate,
      getStatusText,
      getStatusClass,
      submitComment,
      showReplyInput,
      cancelReply,
      submitReply,
      handleDeleteComment,
      canDeleteComment,
      handleSizeChange,
      handleCurrentChange,
      goBack
    }
  }
}
</script>

<style scoped>
.opportunity-detail {
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.basic-info {
  margin-bottom: 30px;
}

.basic-info h1 {
  margin: 0 0 15px;
  font-size: 24px;
}

.meta-info {
  display: flex;
  gap: 20px;
  color: #666;
  margin-bottom: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.status-tag {
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  color: #fff;
}

.status-draft {
  background-color: #909399;
}

.status-published {
  background-color: #67c23a;
}

.status-expired {
  background-color: #f56c6c;
}

.opportunity-content {
  margin-bottom: 40px;
  line-height: 1.8;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.detail-content {
  overflow-wrap: break-word;
}

.detail-content img {
  max-width: 100%;
  height: auto;
}

.comments-section {
  margin-top: 30px;
}

.comments-title {
  margin: 0 0 20px;
  font-size: 18px;
  font-weight: 600;
}

.comment-input {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.comment-input-footer, .reply-input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.remaining-chars {
  color: #909399;
  font-size: 12px;
}

.comment-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.comment-main {
  display: flex;
  gap: 15px;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-weight: 600;
  margin-bottom: 5px;
}

.comment-text {
  margin-bottom: 10px;
  line-height: 1.5;
  word-break: break-word;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #999;
  font-size: 12px;
}

.comment-actions {
  display: flex;
  gap: 10px;
}

.reply-input {
  margin: 10px 0 10px 50px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.reply-actions {
  display: flex;
  gap: 10px;
}

.replies-list {
  margin-left: 50px;
  margin-top: 10px;
}

.reply-item {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.reply-content {
  flex: 1;
}

.reply-user {
  font-size: 14px;
  margin-bottom: 5px;
}

.reply-text {
  margin-bottom: 5px;
  line-height: 1.5;
  word-break: break-word;
}

.reply-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #999;
  font-size: 12px;
}

.reply-actions {
  display: flex;
  gap: 10px;
}

@media (max-width: 768px) {
  .meta-info {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .comment-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .comment-input-footer, .reply-input-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .reply-input-footer .reply-actions {
    margin-top: 5px;
    align-self: flex-end;
  }
}
</style> 